package com.huawei.service.impl;

import cn.hutool.json.JSONUtil;
import com.huawei.domain.LoginUser;
import com.huawei.domain.ResponseResult;
import com.huawei.entity.Users;
import com.huawei.service.ILoginService;
import com.huawei.utils.JwtUtil;
import com.huawei.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(Users user) {

        UsernamePasswordAuthenticationToken noAuthorityAuthentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication hasAuthorityAuthenticate = authenticationManager.authenticate(noAuthorityAuthentication);
        LoginUser loginUser = (LoginUser) hasAuthorityAuthenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();

        //根据用户id生成jwt
        String jwt = JwtUtil.createJWT(userId);
        
        //使用Map封装返回结果
        HashMap<String, Object>  jwtMap = new HashMap<>();

        jwtMap.put("FairyCatAuthorization",jwt);

        //存入Redis
        redisCache.setCacheObject("javaWeb:user:"+userId,loginUser);

        return new ResponseResult(200,"登录成功喵~",jwtMap);

    }

    @Override
    public ResponseResult logout() {
        //获取权限信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        //获取UserDetails的实现类loginUser
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        //获取用户id
        Long id = loginUser.getUser().getId();

        //通过用户id删除Redis中的用户信息
        redisCache.deleteObject("javaWeb:user:"+id);

        return new ResponseResult(200,"退出成功喵~");

    }
}
